import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutterdemo/0demo/database/model.dart';

import 'database_util.dart';

class DatabasePage extends StatefulWidget {
  @override
  _DatabasePageState createState() => _DatabasePageState();
}

class _DatabasePageState extends State<DatabasePage> {

  Model _model;
  @override
  void initState() {
    var db = DatabaseUtil.getInstance();
    db.createDb(DatabaseUtil.CURRENT_DB_VERSION);

    _operateDatabase();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("database"),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            FlatButton(
              onPressed: _mode2jsonStrAndConverse,
              child: Text("model 2 jsonStr and converse, deep copy test"),
            ),
            FlatButton(
              onPressed: (){
                print("_model == $_model");
              },
              child: Text("test deep copy"),
            )
          ],
        ),
      ),
    );
  }

  Future<void> _operateDatabase() async {
    var db = DatabaseUtil.getInstance();
    String name = "lzj";
    await db.insert("userinfo", "insert into userinfo (name) values ('$name')");

    List<Map> userInfoMap = await db.query("select * from userinfo order by _id desc");
    for (Map data in userInfoMap) {
      print(data["_id"]);
    }
    int age = 2;
    await db.insert("student", "insert into student (age) values ('$age')");
    List<Map> studentMap = await db.query("select * from student");
    for (Map data in studentMap) {
      print(data);
      Model model = Model.fromJson(data);
      print(model.iId);
    }
  }

  void _mode2jsonStrAndConverse() {
    Model model = Model();
    model.iId = 1;
    model.age = 2;
    model.name = "li";
    String jsonStr = json.encode(model.toJson());
    print("jsonStr == $jsonStr");
    Model model2 = Model.fromJson(json.decode(jsonStr));
    print("model2 == $model2");

    // test deep copy
    int age = 55;
    model.age = age;
    _model = model;
    print("_model == $_model");
  }
}
